//
//  AppDelegate.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/7/27.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "AppDelegate.h"
#import "BPControllerTool.h"
#import "AFNetworking.h"
#import "MBProgressHUD+MJ.h"
#import "paySuccessViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import "WeiboSDK.h"
#import "APService.h"
#import "Pingpp.h"
#import "UIImageView+WebCache.h"
#import "BaiduMobStat.h"
#import "CoreDateManager.h"
#import "ZBCheckAlasset.h"

@interface AppDelegate ()

@end

@implementation AppDelegate
@synthesize yunIsPost;
@synthesize productIsPost;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    /**  检查网络 **/
    [self checkNetwork];
    
    [self startBaiduMobStat];
    
    //分享功能
    [self shareSdk];
    
    [self jsPushStart:launchOptions];
    
    [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    
    // Override point for customization after application launch.
    
    return YES;
}

- (void)startBaiduMobStat {
    /*若应用是基于iOS 9系统开发，需要在程序的info.plist文件中添加一项参数配置，确保日志正常发送，配置如下：
     NSAppTransportSecurity(NSDictionary):
     NSAllowsArbitraryLoads(Boolen):YES
     详情参考本Demo的BaiduMobStatSample-Info.plist文件中的配置
     */
    BaiduMobStat* statTracker = [BaiduMobStat defaultStat];
    // 此处(startWithAppId之前)可以设置初始化的可选参数，具体有哪些参数，可详见BaiduMobStat.h文件，例如：
    statTracker.shortAppVersion  = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    [statTracker startWithAppId:@"e84feac7e8"]; // 设置您在mtj网站上添加的app的appkey,此处AppId即为应用的appKey
}

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
{
    completionHandler();
}


- (void)jsPushStart:(NSDictionary *)launchOptions
{
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    
    // Required
    [APService setupWithOption:launchOptions];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [APService handleRemoteNotification:userInfo];
    [self PlaySystemSound];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - 推送消息提示声
- (void) PlaySystemSound
{
    NSString* soundName = @"sms-received1";
    NSString* soundType = @"caf";
    // 本地系统音频
    NSString *path = [NSString stringWithFormat:@"/System/Library/Audio/UISounds/%@.%@",soundName,soundType];
    if (path)
    {
        OSStatus error = AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&sound);
        
        if (error != kAudioServicesNoError)
        {//获取的声音的时候，出现错误
            BPLog(@"获取的声音的时候，出现错误");
        }
    }
    // 播放声音
    AudioServicesPlaySystemSound(sound);
    // 手机震动
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

- (void)checkNetwork
{
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 当网络状态改变了，就会调用
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                BPLog(@"没有网络(断网)");
                [MBProgressHUD showError:@"网络异常，请检查网络设置！"];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                BPLog(@"手机自带网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                
                [self postUnimageArry];
                BPLog(@"WIFI");
                break;
        }
    }];
    // 开始监控
    [mgr startMonitoring];
}

- (void)postUnimageArry
{
    CoreDateManager *postMgr = [[CoreDateManager alloc] init];
    NSMutableArray *strArry = [postMgr getAllunpostArry];
    if (strArry.count != 0) {
        ZBCheckAlasset *zbpost = [[ZBCheckAlasset alloc] init];
        [zbpost checkAlaaserArry2:strArry withView:nil];
    }
    
}

- (void)shareSdk
{
    [ShareSDK registerApp:@"967323c5a957"];
    //微博
    [ShareSDK connectSinaWeiboWithAppKey:@"2087144721"
                               appSecret:@"b13f6e4c778af5ada40a8539ddefc42a"
                             redirectUri:@"http://www.len.so"];
    //qq
    [ShareSDK connectQQWithQZoneAppKey:@"1104868646"
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    //qq空间
    [ShareSDK connectQZoneWithAppKey:@"1104868646"
                           appSecret:@"ZYyUb8BHWe92ZX74"
                   qqApiInterfaceCls:[QQApiInterface class]
                     tencentOAuthCls:[TencentOAuth class]];
    
    //微信登陆的时候需要初始化
    [ShareSDK connectWeChatWithAppId:@"wxc285d22556f57574"
                           appSecret:@"d4624c36b6795d1d99dcf0547af5443d"
                           wechatCls:[WXApi class]];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];
    self.yunIsPost = NO;
    self.productIsPost = NO;
    self.backHome = NO;
    self.isEdit = NO;
    [BPControllerTool chooseRootViewController];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url wxDelegate:self];
}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    BPLog(@"%@",url);
//    return [ShareSDK handleOpenURL:url sourceApplication:sourceApplication annotation:annotation wxDelegate:self];
//}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    if ([sourceApplication isEqualToString:@"com.tencent.xin"]) {
        return [ShareSDK handleOpenURL:url sourceApplication:sourceApplication annotation:annotation wxDelegate:self];
    }
    return [Pingpp handleOpenURL:url withCompletion:nil];
}

// iOS 9 以上请用这个
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    return [Pingpp handleOpenURL:url withCompletion:nil];
}

- (void)showPreView
{
    if (_preview == nil) {
        _preview = [[ImageAddPreView alloc] initWithFrame:CGRectMake(0, self.window.frame.size.height - 135, self.window.frame.size.width, 135)];
        [_window addSubview:_preview];
    }
    [_preview setAlpha:0];
    [UIView animateWithDuration:0.2
                          delay:0.1
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [_preview setAlpha:1];
                     } completion:^(BOOL finished) {
                         
                     }];
    [_preview setHidden:NO];
}

- (void)hiddenPreView
{
    [_preview setHidden:YES];
    [_preview setAlpha:0];
        [UIView animateWithDuration:0.1
                              delay:0
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             [_preview setAlpha:0];
                         } completion:^(BOOL finished) {
    
                         }];
}

- (void)showPayView
{
    if (_payView == nil) {
        _payView = [[payView alloc] initWithFrame:CGRectMake(0, self.window.frame.size.height, self.window.frame.size.width, self.window.frame.size.height)];
        [_window addSubview:_payView];
    }
    [UIView animateWithDuration:0.4
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         _payView.frame = CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height);
                     } completion:^(BOOL finished) {
                         [_payView setHidden:NO];
                     }];
    
}

- (void)hidePayView
{
    [UIView animateWithDuration:0.4
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         _payView.frame = CGRectMake(0, self.window.frame.size.height, self.window.frame.size.width, self.window.frame.size.height);
                     } completion:^(BOOL finished) {
                         [_payView setHidden:YES];
                         _payView = nil;
                         
                     }];
    
}

- (void)showDefeatView
{
    if (_defeatView == nil) {
        _defeatView = [[orderDefeat alloc] initWithFrame:CGRectMake(0, self.window.frame.size.height, self.window.frame.size.width, self.window.frame.size.height)];
        [_window addSubview:_defeatView];
    }
    [_defeatView setHidden:NO];
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         _defeatView.frame = CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height);
                     } completion:^(BOOL finished) {
                         
                     }];
    
}

- (void)hideDefeatView
{
    [UIView animateWithDuration:0.5
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         _defeatView.frame = CGRectMake(0, self.window.frame.size.height, self.window.frame.size.width, self.window.frame.size.height);
                     } completion:^(BOOL finished) {
                         [_defeatView setHidden:YES];
                         _defeatView = nil;
                     }];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [[SDImageCache sharedImageCache] clearMemory];
    // 赶紧停止正在进行的图片下载操作
    BPLog(@"内存警告");
}

@end
